package de.breitbeil.jbooking.task;

import java.io.FileOutputStream;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

public class ExcelExportTask extends AbstractTask<Void, Void> {

    private List<Object> objects;
    private List<String> properties;
    private String filename;
    
    public ExcelExportTask(List<Object> objects, List<String> properties, String filename) {
        super("excelExportTask");
        this.objects = objects;
        this.properties = properties;
        
        if(filename.toUpperCase().endsWith(".XLS")) {
            this.filename = filename;
        }
        else {
            this.filename = filename + ".xls";
        }
    }

    @Override
    protected Void doInBackground() throws Exception {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();
        
        int rowNr = 0;
        int columnNr = 0;
        
        for(Object o: objects) {
            BeanWrapper beanWrapper = new BeanWrapperImpl(o);
            HSSFRow row = sheet.createRow(rowNr);
            
            for(String property: properties) {
                 Object value = beanWrapper.getPropertyValue(property);
                 String valueAsString = (value == null)? "" : value.toString();

                 HSSFCell cell = row.createCell(columnNr);
                 cell.setCellValue(valueAsString);
                 
                 columnNr++;
            }
            
            rowNr++;
            columnNr = 0;
        }

        FileOutputStream out = new FileOutputStream(filename);
        try {
            workbook.write(out);
        }
        finally {
            out.close();
        }
        
        return null;
    }

}
